package com.UdpRecieve.tool;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.*;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;

/**
 * 文件处理工具类
 *
 * @author ruoyi
 */
public class FileUtil
{
    public static String FILENAME_PATTERN = "[a-zA-Z0-9_\\-\\|\\.\\u4e00-\\u9fa5]+";
    public static final String separator = File.separator;
    /**
     * 读取文件成byte数组
     * @param filePaht 文件地址
     * @return
     */
    public static byte[] readFileToByteArray(String filePaht) {
        // 文件输入流（需要关闭）
        InputStream is = null;
        try {
            is = new FileInputStream(new File(filePaht));
            // 字节数组输出流（不需要关闭）
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buf = new byte[1024 * 1];
            int len;
            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 下载样表
     * @param filePath 文件上级目录
     * @param fileName 文件名
     * @param newName  下载的展示文件名+扩展名
     * @return 响应
     */
    public static ResponseEntity<InputStreamResource> downloadXML(String filePath, String fileName, String newName) {
        //String route = "static" + separator + "file" + separator;
        String path = null;
        ResponseEntity<InputStreamResource> response = null;
        try {
            path = filePath + separator + fileName;
            //ClassPathResource classPathResource = new ClassPathResource(path);
            InputStream inputStream = new FileInputStream(path);
            HttpHeaders headers = new HttpHeaders();
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Content-Disposition",
                    "attachment; filename="
                            + new String(newName.getBytes("utf-8"), "iso8859-1"));
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            response = ResponseEntity.ok().headers(headers)
                    .contentType(MediaType.parseMediaType("application/octet-stream"))
                    .body(new InputStreamResource(inputStream));
        } catch (FileNotFoundException e1) {
            //log.error("找不到指定的文件", e1);
            e1.printStackTrace();
        } catch (IOException e) {
            //log.error("获取不到文件流", e);
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 把byte数组写成文件
     * @param datas 文件的byte数组
     * @param destFileName 文件地址
     * @return
     */
    public  String writeByteArrayToFile(byte[] datas, String destFileName) {
        // 文件输出流（需要关闭）
        OutputStream os = null;
        try {
            // 字节数组输入流（不需要关闭）
            InputStream is = new ByteArrayInputStream(datas);
            os = new FileOutputStream(new File(destFileName));

            byte[] buf = new byte[1024];
            int len;
            while (((len = is.read(buf)) != -1)) {
                os.write(buf, 0, len);
            }
            os.flush();
            return "成功!";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "失败!";
        } catch (IOException e) {
            e.printStackTrace();
            return "失败!";
        } finally {
            if (os != null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 输出指定文件的byte数组
     *
     * @param filePath 文件路径
     * @param os 输出流
     * @return
     */
    public static void writeBytes(String filePath, OutputStream os) throws IOException
    {
        FileInputStream fis = null;
        try
        {
            File file = new File(filePath);
            if (!file.exists())
            {
                throw new FileNotFoundException(filePath);
            }
            fis = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length;
            while ((length = fis.read(b)) > 0)
            {
                os.write(b, 0, length);
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            if (os != null)
            {
                try
                {
                    os.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (fis != null)
            {
                try
                {
                    fis.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     *
     * @param filePath 文件全路径
     * @return
     */
    public static boolean deleteFile(String filePath)
    {
        boolean flag = false;
        File file = new File(filePath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists())
        {
            file.delete();
            flag = true;
        }
        return flag;
    }

    /**
     * 文件名称验证
     *
     * @param filename 文件名称
     * @return true 正常 false 非法
     */
    public static boolean isValidFilename(String filename)
    {
        return filename.matches(FILENAME_PATTERN);
    }

    /**
     * 下载文件名重新编码
     *
     * @param request 请求对象
     * @param fileName 文件名
     * @return 编码后的文件名
     */
    public static String setFileDownloadHeader(HttpServletRequest request, String fileName)
            throws UnsupportedEncodingException
    {
        final String agent = request.getHeader("USER-AGENT");
        String filename = fileName;
        if (agent.contains("MSIE"))
        {
            // IE浏览器
            filename = URLEncoder.encode(filename, "utf-8");
            filename = filename.replace("+", " ");
        }
        else if (agent.contains("Firefox"))
        {
            // 火狐浏览器
            filename = new String(fileName.getBytes(), "ISO8859-1");
        }
        else if (agent.contains("Chrome"))
        {
            // google浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        else
        {
            // 其它浏览器
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

    /**
     * 递归删除文件夹下所有内容
     * @param file 文件夹目录
     * @return
     */
    public static Boolean deleteFiles(File  file){
        File [] b = file.listFiles();//获取包含file对象对应的子目录或者文件
        for(int i =0;i<b.length;i++){
            if(b[i].isFile()){//判断是否为文件
                b[i].delete();//如果是就删除
            }else{
                return deleteFiles(b[i]);//否则重新递归到方法中
            }
        }
        return file.delete();//最后删除该目录中所有文件后就删除该目录
    }



    /**
     * 文件拷贝
     * @param sourcePath 文件源目录(不带文件名)
     * @param targetPath 文件拷贝目录(不带文件名)
     * @param FileName 文件名.后缀
     * @throws IOException
     */
    public static void copyFileUsingFileStreams(String sourcePath,String targetPath,String FileName) throws IOException {
        InputStream input = null;
        OutputStream output = null;
        File source = new File(sourcePath+File.separator+FileName);
        File destPath = new File(targetPath);
        if(!destPath.exists()){
            destPath.mkdirs();
        }
        File dest = new File(targetPath+File.separator+FileName);
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf))!= -1) {
                output.write(buf, 0, bytesRead);
            }
        } finally {
            input.close();
            output.close();
        }
    }

    /**
     * 先根遍历序递归删除文件夹
     *
     * @param dirFile 要被删除的文件或者目录
     * @return 删除成功返回true, 否则返回false
     */
    public static boolean deleteFile(File dirFile) {
        // 如果dir对应的文件不存在，则退出
        if (!dirFile.exists()) {
            return false;
        }

        if (dirFile.isFile()) {
            return dirFile.delete();
        } else {

            for (File file : dirFile.listFiles()) {
                deleteFile(file);
            }
        }

        return dirFile.delete();
    }

    public static void main(String[] args) {
        FileUtil.deleteFile(new File("F:\\Home02\\Send02\\文件.zip"));
    }




}

